<script setup lang="ts">
import {onMounted, onUnmounted, ref} from 'vue';
import ThemeSwitcher from '@/components/ThemeSwitcher.vue';
import {useRouter} from 'vue-router';
import {App} from '@/model/App.ts'
import emitter from '@/bus/eventBus.ts';
import {CacheApp, LocalStorage} from "@/utils/cache.ts";
import {Notification} from "@arco-design/web-vue";

// 获取路由
const router = useRouter();

// 定义应用列表数据
const apps = ref<Array<CacheApp>>([] as Array<CacheApp>);

// 定义当前应用ID数据
const currentAppId = ref<string>('');


/**
 * @function headerAppCheck
 * @description 导航到应用对应的charts详情列表页面
 * @author xincan
 * @date 2023-05-09
 * @param app 应用信息
 */
const headerAppCheck = async (app: CacheApp) => {
  currentAppId.value = app.id;
  apps.value = new LocalStorage('select', new App(app.id, app.name, app.url,'','', app.selected)).updateCache()
  await router.replace({name: 'Repos', query: {appId: app.id}});
};

/**
 * @function headerAppCheckClose
 * @description 删除应用
 * @author xincan
 * @date 2023-05-09
 * @param closeApp 应用信息
 */
const headerAppCheckClose = async (closeApp: CacheApp) => {
  // 更新缓存
  const store = new LocalStorage('get').store
  if (store.length === 0) {
    Notification.warning({content: '暂无数据'});
    return
  }
  // 获取对象中selected为true的 应用
  const selectedApps = store.filter((app: CacheApp) => app.selected);
  // 判断app是否在应用列表中, 如果不在则直接删除不用跳转, 否则跳转到应用列表页面
  selectedApps.forEach((app: CacheApp) => {
    if (closeApp.id === app.id && closeApp.selected === app.selected) {
      router.replace({name: 'Apps'});
    }
  });
  apps.value = new LocalStorage('delete', new App(closeApp.id, closeApp.name, closeApp.url,'','', closeApp.selected)).updateCache()

}

/**
 * @function handleThemeChange
 * @description 处理主题切换事件
 * @author xincan
 * @date 2023-05-09
 * @param theme - 新主题名称
 */
const handleThemeChange = async (theme: string) => {
  const root = document.documentElement;

  // 移除所有主题相关的class
  root.classList.remove('theme-purple-dark', 'theme-blue-dark', 'theme-green-dark', 'theme-red-dark');

  // 添加新主题的class
  root.classList.add(`theme-${theme}`);

  // 保存主题设置到 localStorage
  localStorage.setItem('theme', theme);
};

/**
 * @function loadStoredApps
 * @description 从localStorage中读取已选应用, 并更新应用列表数据
 * @author xincan
 * @date 2023-05-09
 */
const loadStoredApps = async () => {
  const storedApps: Array<CacheApp> = JSON.parse(localStorage.getItem('selectedApps') || '[]');
  if (storedApps != null) {
    apps.value = storedApps
  }
};

onMounted(async () => {

  // 初始化主题
  const savedTheme = localStorage.getItem('theme') || 'purple-dark';
  await handleThemeChange(savedTheme);

  // 初始化加载缓存数据
  await loadStoredApps();

  // 组件挂载后，开始监听 apps-header 事件
  emitter.on('apps-header', loadStoredApps);
});

onUnmounted(() => {
  // 组件卸载前，移除对 apps-heade 事件的监听
  emitter.off('apps-header', loadStoredApps);
});
</script>

<template>

  <a-row justify="space-between" align="start">
    <a-col flex="240px">
      Charts Manager
    </a-col>
    <a-col>
      <a-space>
        <a-tooltip v-for="app of apps as Array<CacheApp>" :content="app.name">
        <a-tag
            :key="app.id"
            closable
            checkable
            :checked="app.selected"
            :default-checked="app.selected"
            :class="{ 'app-tag-active': app.selected }"
            @click="headerAppCheck(app)"
            @close="headerAppCheckClose(app)"
        >
          <div class="tag-content">{{ app.name }}</div>
        </a-tag>
        </a-tooltip>
      </a-space>
    </a-col>
    <a-col flex="240px">
      <theme-switcher @change="handleThemeChange"/>
    </a-col>
  </a-row>
</template>

<style lang="scss" scoped>

.arco-row {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  white-space: nowrap;
}

.arco-col {
  height: 48px;
  line-height: 48px;
  color: var(--color-white);
  text-align: center;
}

.arco-col:nth-child(1) {
  text-align: left;
  font-size: 22px;
  font-weight: 500;
  color: var(--theme-primary);
}

.arco-col:nth-child(2) {
  width: 100%;
  display: flex;
  flex: 1;
  justify-content: flex-start;
  overflow-x: auto;
  white-space: nowrap;
  // 隐藏滚动条但仍保持滚动功能
  scrollbar-width: none;
  -ms-overflow-style: none;

  &::-webkit-scrollbar {
    display: none;
  }

  :deep(.arco-space) {
    flex-wrap: nowrap;
    width: 0;
  }

  :deep(.arco-tag) {
    flex-shrink: 0;
    white-space: nowrap;
    .tag-content {
      max-width: 100px;
      overflow: hidden;
      text-overflow: ellipsis;
    }

  }
}

.arco-col:nth-child(3) {
  display: flex;
  align-items: center;
  justify-content: flex-end; /* 让子元素靠右对齐 */
}


</style>
